package top.lixunda.common.validate.validate;

import top.lixunda.common.validate.annotation.XumNotNull;
import top.lixunda.common.validate.core.ValidateError;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;

/**
 * @author Xumda
 * @version time:2019/12/9 13:15
 */
public class NotNullValidate implements AnnotationValidate {

    @Override
    public boolean support(Class annotationClass) {
        return XumNotNull.class.equals(annotationClass);
    }

    @Override
    public ValidateError valid(Annotation annotation, Field field, Object obj, Object value, AnnotationCacheValidate handler) {
        XumNotNull a = (XumNotNull) annotation;
        //noinspection ConstantConditions
        return value != null ? null :
                new ValidateError(getErrorMessage(a.message(), field, value));
    }

    private String getErrorMessage(String message, Field field, Object value) {
        return "".equals(message) ? field.getName() + "不能为空"
                : message.replaceAll("#value#", "null").replaceAll("#name#", field.getName());
    }

}
